<template>
  <div style="color: red">深浅拷贝</div>
  <br />
  <div>实现浅拷贝的方法:1.遍历 2.Object.create</div>
  <div>实现深拷贝的方法:1.遍历（手写深拷贝） 2.JSON.parse和JSON.stringify</div>

  <hr />

  <div v-for="item in arr2" :key="item">{{ item }}</div>
  <hr />

  <div>{{ person.d.f.g }}</div>
  <div>{{ deepCopy2.d.f.g }}</div>
</template>

<script setup lang="ts">
import { deepCopy } from "@/tools/tools";
import { reactive, ref } from "vue";
// 浅拷贝
// 1.遍历
const obj = {
  a: 1,
  c: {
    name: "hello",
    d: "3",
  },
  d: [1, 2, 3, 4, 5, 6, 7, 8, 9],
};
interface obj {
  name: string;
  d: string;
}
interface objInter {
  a: number;
  c: obj;
  d: number[];
}

const objCopy = (obj: objInter): objInter => {
  const copyObj = {};
  for (let item in obj) {
    copyObj[item] = obj[item];
  }

  return copyObj as objInter;
};
const res = objCopy(obj);
res.c.d = "520";
console.log(obj);
console.log(res);
console.log("@@@@@@@@@@@@@@@@@@");
// 2.Object.create()

const obj4 = reactive<objInter>({
  a: 1,
  c: {
    name: "hello",
    d: "3",
  },
  d: [1, 2, 3, 4, 5, 6, 7, 8, 9],
});
interface obj {
  name: string;
  d: string;
}
const obj3 = Object.create(obj4);
obj3.c.d = "555";
console.log(obj4);
console.log(obj3);

// 2.深拷贝
// 1.遍历
const person = {
  name: "sq",
  hobby: "网球",
  contact: "18423152509",
  d: {
    c: "机车",
    f: {
      g: "nihoa",
    },
    h: [1, 2, 3],
    j: () => {
      return 123;
    },
  },
};

const deepPerson = deepCopy(person);
deepPerson.d.j = () => {
  return 555;
};
deepPerson.d.f.g = "hello";
console.log(person);
console.log(deepPerson);

// 2.JSON.parse 配合JSON.stringify

const person2 = {
  name: "sq",
  hobby: "网球",
  contact: "18423152509",
  d: {
    c: "机车",
    f: {
      g: "nihoa",
    },
    h: [1, 2, 3],
    j: () => {
      return 123;
    },
  },
};
const deepCopy2 = JSON.parse(JSON.stringify(person2));
deepCopy2.d.f.g = "465465";
console.log(person2);
console.log(deepCopy2);

const promiseFun = (arr: Array<number>) => {
  return new Promise((resolve, reject) => {
    const res = arr.map((item) => {
      return item * 2;
    });
    resolve(res);
  });
};

const arr = [1, 8, 2, 6];
const arr2 = ref<number[]>([]);

promiseFun(arr).then((res: Array<number>) => {
  res[0] = 555;
  arr2.value = res;
  console.log("1$$$$", res);
});

</script>

<style scoped lang="scss"></style>
